#include "cmdsql.h"
#include "dbctrl.h"

CT_REGISTER_ASYNCCMD(ID_DB_SQL, CCmdSQL);

CCmdSQL::CCmdSQL()
{
    m_pstMain = NULL;
    m_pstStream = NULL;
}

CCmdSQL::~CCmdSQL()
{

}

int CCmdSQL::Do(void* pData)
{
    CT_ASSERT(m_pstMain != NULL);
    CT_ASSERT(m_stReq.stSQL[0] != '\0');
	CT_ASSERT(pData);
	CEnpNetHead* pstHead = (CEnpNetHead*)pData;

    int iRet = 0;

    CTMsgHead stMsgHead;
    stMsgHead.shMsgID = ID_DB_SQL;
    stMsgHead.shMsgType = EMT_REQUEST;
    stMsgHead.iCmdSeq = GetCmdSeq();
    stMsgHead.llMsgAct = reinterpret_cast<int64>(this);// 重要! 回调时时需要

    CTBuffer& stBuf = m_pstMain->m_stEncodeBuf;
    stBuf.Clear();
    CTCodeStream s(stBuf);
	s.m_ushPos = sizeof(CEnpNetHead);

    CodeConvert(s, stMsgHead, NULL, bin_encode());
    CT_TRACE(("sql length %d, %s", m_stReq.stSQLMen.GetDataLen(), m_stReq.GetSqlBuffer()));
    CodeConvert(s, m_stReq, NULL, bin_encode());
    if (s.m_iRet)
    {
        CT_WARNING((""));
        return Done(RET_SYSTEM_FAIL);
    }

	pstHead->unDataLength = s.m_ushPos - sizeof(CEnpNetHead);
	memcpy(s.m_pszBuf, pstHead, sizeof(CEnpNetHead));
    iRet = m_pstMain->RequestToMp(s.m_pszBuf, s.m_ushPos);
    if (iRet)
    {
        CT_WARNING((""));
        return Done(RET_SYSTEM_FAIL);
    }

    return 0;  // 消息没处理完就不调用Done
}

int CCmdSQL::OnAnswer(void* pData)
{
    CT_ASSERT(pData);

    CCmdOnAnswerParam* pstParam = (CCmdOnAnswerParam*) pData;
    CT_ASSERT(((CDBCtrl*)(pstParam->m_pMain)) == m_pstMain);
    CT_ASSERT(pstParam->m_pstMsgHead->shMsgID == ID_DB_SQL &&
        pstParam->m_pstMsgHead->shMsgType == EMT_ANSWER);

    int iRet = 0;

    // 解析请求
    m_pstStream = pstParam->m_pstCode;
    CT_ASSERT(m_pstStream != NULL);

    iRet = CodeConvert(*m_pstStream, m_stResult, NULL, bin_decode());
    if (iRet)
    {
        CT_TRACE(("CodeConvert failed, ret=%d", iRet));
        return Done(RET_INVALID_PARAM);
    }

    // 数据转换
    if (m_stResult.m_iResult)
    {
        CT_WARNING(("cmdsql execute sql failed, ret=%d", m_stResult.m_iResult));
        return Done(RET_SYSTEM_FAIL);
    }
    else
    {
        return Done(RET_OK);
    }
}
